package freighttmpl

import (
	"context"
	"strconv"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/moneyx"
	enum "mall/service/backend/common/enum/setting"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetFreightTemplateByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetFreightTemplateByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetFreightTemplateByIdLogic {
	return &GetFreightTemplateByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// group: freighttmpl
func (l *GetFreightTemplateByIdLogic) GetFreightTemplateById(in *setting.IDReq) (*setting.FreightTemplateInfo, error) {
	res, err := l.svcCtx.FreightTemplate.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if res.Status != uint8(globalkey.StatusEnabled) {
		return nil, errorx.NewNotFoundError("setting.freightTemplateNotExists")
	}

	var restrictions []*setting.FreightTemplateRestrictionInfo
	filterMap := make(map[string]map[string][]any)
	filterMap[model.SysFreightTemplateRestrictionColumns.TemplateID] = map[string][]any{
		"equalTo": []any{in.Id},
	}
	list, _, err := l.svcCtx.FreightTemplate.GetRestrictionList(l.ctx, model.M{
		"orderBy": model.SysFreightTemplateRestrictionColumns.Sort + " DESC",
	}, -1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(list) > 0 {
		for _, v := range list {
			var threshold *string
			switch v.Mode {
			case enum.FreightTemplateRestrictionAmount:
				threshold = pointy.GetPointer(moneyx.FormatAmount(int64(v.Threshhold)))
			case enum.FreightTemplateRestrictionNumber:
				threshold = pointy.GetPointer(strconv.FormatInt(int64(v.Threshhold), 10))
			}
			var regions *string
			if v.Regions.Valid {
				regions = pointy.GetPointer(string(v.Regions.JSON))
			}
			restrictions = append(restrictions, &setting.FreightTemplateRestrictionInfo{
				Id:         &v.RestrictionID,
				TemplateId: &v.TemplateID,
				Regions:    regions,
				Mode:       pointy.GetPointer(uint32(v.Mode)),
				Threshold:  threshold,
				Sort:       pointy.GetPointer(uint32(v.Sort)),
				Status:     pointy.GetPointer(uint32(v.Status)),
			})
		}
	}

	var rules []*setting.FreightTemplateRuleInfo
	ruleFilterMap := make(map[string]map[string][]any)
	ruleFilterMap[model.SysFreightTemplateRuleColumns.TemplateID] = map[string][]any{
		"equalTo": []any{in.Id},
	}
	ruleFilterMap[model.SysFreightTemplateRuleColumns.ChargeMode] = map[string][]any{
		"equalTo": []any{res.ChargeMode},
	}
	ruleList, _, err := l.svcCtx.FreightTemplate.GetRuleList(l.ctx, model.M{
		"orderBy": model.SysFreightTemplateRuleColumns.Sort + " DESC",
	}, -1, ruleFilterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(ruleList) > 0 {
		for _, v := range ruleList {
			var regions *string
			if v.Regions.Valid {
				regions = pointy.GetPointer(string(v.Regions.JSON))
			}

			var firstUnit string
			var continueUnit string
			switch res.ChargeMode {
			case enum.FreightTemplateRuleNumber:
				firstUnit = strconv.FormatInt(int64(v.FirstUnit), 10)
				continueUnit = strconv.FormatInt(int64(v.ContinueUnit), 10)
			case enum.FreightTemplateRuleWeight:
				firstUnit = moneyx.FormatWeight(int64(v.FirstUnit))
				continueUnit = moneyx.FormatWeight(int64(v.ContinueUnit))
			case enum.FreightTemplateRuleVolume:
				firstUnit = moneyx.FormatVolume(int64(v.FirstUnit))
				continueUnit = moneyx.FormatVolume(int64(v.ContinueUnit))
			}

			firstPrice := moneyx.FormatAmount(int64(v.FirstPrice))
			continuePrice := moneyx.FormatAmount(int64(v.ContinuePrice))

			rules = append(rules, &setting.FreightTemplateRuleInfo{
				Id:            &v.RuleID,
				TemplateId:    &v.TemplateID,
				Regions:       regions,
				ChargeMode:    pointy.GetPointer(uint32(v.ChargeMode)),
				FirstUnit:     &firstUnit,
				FirstPrice:    &firstPrice,
				ContinueUnit:  &continueUnit,
				ContinuePrice: &continuePrice,
				Sort:          pointy.GetPointer(uint32(v.Sort)),
				Status:        pointy.GetPointer(uint32(v.Status)),
			})
		}
	}

	return &setting.FreightTemplateInfo{
		Id:           &res.ID,
		Name:         &res.Name,
		Remark:       &res.Remark,
		FreeShipping: pointy.GetPointer(uint32(res.FreeShipping)),
		ChargeMode:   pointy.GetPointer(uint32(res.ChargeMode)),
		Sort:         pointy.GetPointer(uint32(res.Sort)),
		Status:       pointy.GetPointer(uint32(res.Status)),
		CreatedAt:    pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt:    pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt:    pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
		Restrictions: restrictions,
		Rules:        rules,
	}, nil
}
